package com.autonavi.minimap.util.TaskEngine;

import java.util.ArrayList;

import android.util.SparseArray;

import com.autonavi.minimap.threadpool.IDThreadPool;
import com.autonavi.minimap.threadpool.IPriorityTask;

public abstract class BaseProrityTask<E> implements IPriorityTask {
	private IDThreadPool pool;
	private String category = "";
	private int retry = 3;
	protected SparseArray<E> lsts = new SparseArray<E>();
	private String flag;

	public BaseProrityTask(String flag, E listener) {
		this.flag = flag;
		if(listener!=null){
			lsts.put(this.hashCode(), listener);
		}
	}
	
	public void set(IDThreadPool pool, int retry, String category) {
		this.pool = pool;
		this.category = category;
		this.retry = retry;
	}

	protected void retry() {
		if (--retry > 0) {
			pool.put(category, this);
		}
	}

	protected int getRetryDelay() {
		return 0;
	}

	protected ArrayList<E> getListeners() {
		ArrayList<E> result = new ArrayList<E>();
		final int length = lsts.size();
		E temp;
		for(int i=0;i<length;i++){
			temp = lsts.valueAt(i);
			if(temp!=null){
				result.add(temp);
			}
		}
		return result;
	}
	
	@Override
	public String getFlag() {
		return flag;
	}

	@Override
	public void isolateFlag() {
		flag += System.currentTimeMillis();
	}

	@Override
	public boolean onRepeatPut(IPriorityTask newTask) {
		if (!(newTask instanceof BaseProrityTask)) {
			return false;
		}
		BaseProrityTask<E> nt = (BaseProrityTask<E>) newTask;
		ArrayList<E> listener = nt.getListeners();
		if (listener != null) {
			synchronized (lsts) {
				for (E l : listener) {
					if (lsts.indexOfValue(l)<0) {
						lsts.put(nt.hashCode(),l);
					}
				}
			}
		}
		return true;
	}
	
	@Override
	public boolean unregisterListener(int taskId) {
		lsts.delete(taskId);
		return lsts.size()<1;
	}

}
